<template>
  <div class="inventory-card card">
    <div class="card-header">
      <i class="fas fa-pills card-icon"></i>
      <span class="card-title">药品库存管理</span>
      <div class="card-actions">
        <button class="btn-export" @click="handleExport">
          <i class="fas fa-file-export"></i>
          导出
        </button>
        <button class="btn-import" @click="handleImport">
          <i class="fas fa-file-import"></i>
          导入
        </button>
        <button class="btn-refresh" @click="$emit('refresh')">
          <i class="fas fa-sync-alt"></i>
          刷新
        </button>
      </div>
    </div>
    <div class="card-content">
      <div class="search-box">
        <input
          type="text"
          :value="search"
          @input="handleSearchInput"
          placeholder="搜索药品名称..."
          class="search-input"
        >
        <i class="fas fa-search search-icon"></i>
      </div>

      <div class="notice-board" v-if="lowStockMedicines.length > 0">
        <div class="notice-header">
          <i class="fas fa-bell"></i>
          <span>库存不足提醒</span>
        </div>
        <div class="notice-content">
          <div class="notice-marquee">
            <div class="marquee-content">
              <span
                v-for="(medicine, index) in lowStockMedicines"
                :key="index"
                class="medicine-alert"
              >
                <span class="alert-text">药品</span>
                <span class="medicine-name-alert">{{ medicine.name }}</span>
                <span class="alert-text">库存仅剩</span>
                <span class="stock-number">{{ medicine.stock }}</span>
                <span class="alert-text">件，急需补货！</span>
              </span>
            </div>
          </div>
        </div>
      </div>

      <div class="inventory-list">
        <div
          v-for="medicine in sortedFilteredMedicines"
          :key="medicine.id"
          class="inventory-item"
          :class="{ 'low-stock': medicine.stock < medicine.minStock }"
        >
          <div class="medicine-main">
            <span class="medicine-icon">{{ medicine.icon }}</span>
            <div class="medicine-info">
              <h4 class="medicine-name">{{ medicine.name }}</h4>
              <span class="medicine-category">{{ medicine.category }}</span>
            </div>
          </div>
          <div class="medicine-stats">
            <div class="stock-info">
              <span class="stock-count">{{ medicine.stock }}</span>
              <span class="stock-label">库存</span>
            </div>
            <div class="status-indicator" :class="getStockStatus(medicine)">
              {{ getStockStatusText(medicine) }}
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 导入模态框 -->
    <div v-if="showImportModal" class="import-modal" @click="closeImportModal">
      <div class="import-modal-content" @click.stop>
        <div class="import-modal-header">
          <h3>导入药品库存数据</h3>
          <button class="close-button" @click="closeImportModal">&times;</button>
        </div>
        <div class="import-modal-body">
          <div
            class="drop-area"
            :class="{ 'drag-over': isDragging }"
            @dragover.prevent
            @dragenter.prevent="isDragging = true"
            @dragleave.prevent="isDragging = false"
            @drop.prevent="handleFileDrop"
          >
            <i class="fas fa-cloud-upload-alt upload-icon"></i>
            <p>将 .xls 文件拖拽到此处上传</p>
            <p class="upload-hint">仅支持 Excel 97-2003 工作簿 (.xls) 格式</p>
          </div>

          <div class="template-download">
            <h4>下载模板</h4>
            <p>如需模板，请点击下方按钮下载</p>
            <button class="btn-download-template" @click="downloadTemplate">
              <i class="fas fa-download"></i>
              下载模板文件
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'

// 定义props
const props = defineProps({
  medicines: {
    type: Array,
    required: true
  },
  search: {
    type: String,
    default: ''
  }
})

// 定义事件
const emit = defineEmits(['search-change', 'refresh', 'import'])

// 导入相关状态
const showImportModal = ref(false)
const isDragging = ref(false)

// 计算属性
const filteredMedicines = computed(() => {
  if (!props.search) return props.medicines
  return props.medicines.filter(medicine =>
    medicine.name.toLowerCase().includes(props.search.toLowerCase())
  )
})

// 新增计算属性：优先显示库存不足的药品
const sortedFilteredMedicines = computed(() => {
  const lowStock = []
  const normalStock = []

  filteredMedicines.value.forEach(medicine => {
    if (medicine.stock < medicine.minStock) {
      lowStock.push(medicine)
    } else {
      normalStock.push(medicine)
    }
  })

  return [...lowStock, ...normalStock]
})

const lowStockMedicines = computed(() => {
  return props.medicines.filter(medicine =>
    medicine.stock < medicine.minStock
  )
})

// 方法
const handleSearchInput = (event) => {
  emit('search-change', event.target.value)
}

const getStockStatus = (medicine) => {
  if (medicine.stock === 0) return 'out-of-stock'
  if (medicine.stock < medicine.minStock) return 'low-stock'
  return 'in-stock'
}

const getStockStatusText = (medicine) => {
  if (medicine.stock === 0) return '缺货'
  if (medicine.stock < medicine.minStock) return '库存不足'
  return '库存充足'
}

const handleImport = () => {
  showImportModal.value = true
}

const closeImportModal = () => {
  showImportModal.value = false
  isDragging.value = false
}

const handleFileDrop = (event) => {
  isDragging.value = false
  const files = event.dataTransfer.files

  if (files.length > 0) {
    const file = files[0]

    if (file.name.endsWith('.xls') || file.name.endsWith('.xlsx')) {
      uploadFile(file)
    } else {
      alert('仅支持 .xls 格式的文件')
    }
  }
}

const uploadFile = async (file) => {
  const formData = new FormData()
  formData.append('file', file)

  try {
    const response = await fetch('/medicine/medicine/importData', {
      method: 'POST',
      body: formData
    })
    
    if (response.ok) {
      const result = await response.json()
      console.log('导入成功:', result)
      closeImportModal()
      emit('refresh')
    } else {
      throw new Error('导入失败')
    }
  } catch (error) {
    console.error('导入失败:', error)
    alert('文件导入失败')
  }
}

const downloadTemplate = async () => {
  try {
    const response = await fetch('/api/medicine/template')
    if (response.ok) {
      const blob = await response.blob()
      const url = window.URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = '药品库存模板.xls'
      a.click()
      window.URL.revokeObjectURL(url)
    } else {
      throw new Error('模板下载失败')
    }
  } catch (error) {
    console.error('模板下载失败:', error)
    alert('模板下载失败')
  }
}

const handleExport = async () => {
  try {
    const response = await fetch('/medicine/medicine/export', {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ /* 查询参数 */ })
    })
    
    if (response.ok) {
      const blob = await response.blob()
      const url = window.URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = 'medicine.xlsx'
      document.body.appendChild(a)
      a.click()
      document.body.removeChild(a)
      window.URL.revokeObjectURL(url)
    } else {
      throw new Error('导出失败')
    }
  } catch (error) {
    console.error('导出失败:', error)
    alert('导出失败')
  }
}
</script>

<style scoped>
.card {
  background: white;
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  border: 1px solid rgba(255, 255, 255, 0.8);
  backdrop-filter: blur(10px);
  transition: all 0.3s ease;
  margin-bottom: 20px;
  position: relative;
}

.card:hover {
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12);
  transform: translateY(-2px);
}

.card-header {
  display: flex;
  align-items: center;
  padding: 20px 24px 16px;
  border-bottom: 1px solid #f0f2f5;
}

.card-icon {
  font-size: 20px;
  color: #4a6cf7;
  margin-right: 10px;
}

.card-title {
  font-size: 18px;
  font-weight: 600;
  color: #1a1a1a;
  flex: 1;
}

.card-actions {
  margin-left: auto;
  display: flex;
  gap: 10px;
}

.btn-import {
  background: #4a6cf7;
  border: none;
  padding: 8px 16px;
  border-radius: 10px;
  font-size: 14px;
  color: white;
  cursor: pointer;
  transition: all 0.3s;
  display: flex;
  align-items: center;
  gap: 6px;
}

.btn-import:hover {
  background: #3a5ce5;
  transform: translateY(-2px);
}

.btn-refresh {
  background: #e8eaf0;
  border: none;
  padding: 8px 16px;
  border-radius: 10px;
  font-size: 14px;
  color: #555;
  cursor: pointer;
  transition: all 0.3s;
  display: flex;
  align-items: center;
  gap: 6px;
}

.btn-refresh:hover {
  background: #d0d0d0;
  transform: translateY(-2px);
}

.btn-export {
  background: #0ca678;
  border: none;
  padding: 8px 16px;
  border-radius: 10px;
  font-size: 14px;
  color: white;
  cursor: pointer;
  transition: all 0.3s;
  display: flex;
  align-items: center;
  gap: 6px;
}

.btn-export:hover {
  background: #099268;
  transform: translateY(-2px);
}

.card-content {
  padding: 20px 24px;
}

.search-box {
  position: relative;
  margin-bottom: 20px;
}

.search-input {
  width: 100%;
  padding: 12px 40px 12px 16px;
  border: 2px solid #e8eaf0;
  border-radius: 10px;
  font-size: 14px;
  transition: all 0.3s;
  background: #fafbfc;
}

.search-input:focus {
  border-color: #4a6cf7;
  background: white;
  box-shadow: 0 0 0 3px rgba(74, 108, 247, 0.1);
  outline: none;
}

.search-icon {
  position: absolute;
  right: 16px;
  top: 50%;
  transform: translateY(-50%);
  color: #8f9bb3;
}

.notice-board {
  background: linear-gradient(135deg, #ff9a9e 0%, #fad0c4 100%);
  border-radius: 12px;
  padding: 15px;
  margin-bottom: 20px;
  box-shadow: 0 4px 12px rgba(255, 154, 158, 0.3);
}

.notice-header {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
  color: #d32f2f;
  font-weight: bold;
}

.notice-header i {
  margin-right: 8px;
  font-size: 18px;
  animation: bell-ring 1s infinite;
}

@keyframes bell-ring {
  0% { transform: rotate(0); }
  15% { transform: rotate(15deg); }
  30% { transform: rotate(-10deg); }
  45% { transform: rotate(5deg); }
  60% { transform: rotate(-5deg); }
  75% { transform: rotate(2deg); }
  100% { transform: rotate(0); }
}

.notice-content {
  overflow: hidden;
  white-space: nowrap;
}

.notice-marquee {
  display: inline-block;
  animation: marquee 15s linear infinite;
}

.marquee-content {
  display: inline-block;
  padding-left: 100%;
}

@keyframes marquee {
  0% { transform: translateX(0); }
  100% { transform: translateX(-100%); }
}

.medicine-alert {
  display: inline-block;
  padding: 0 15px;
}

.medicine-alert .alert-text {
  color: #5a5a5a;
  margin: 0 5px;
}

.medicine-alert .medicine-name-alert {
  color: #d32f2f;
  font-weight: bold;
  margin: 0 5px;
}

.medicine-alert .stock-number {
  color: #d32f2f;
  font-weight: bold;
  margin: 0 5px;
}

.inventory-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
  max-height: 500px;
  overflow-y: auto;
}

.inventory-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px;
  border: 2px solid #e8eaf0;
  border-radius: 12px;
  transition: all 0.3s;
  background: #f8f9fc;
}

.inventory-item:hover {
  border-color: #4a6cf7;
  transform: translateY(-2px);
}

.inventory-item.low-stock {
  background: #fff9e6;
  border-color: #ffd166;
}

.medicine-main {
  display: flex;
  align-items: center;
  gap: 12px;
}

.medicine-icon {
  font-size: 24px;
}

.medicine-info {
  display: flex;
  flex-direction: column;
}

.medicine-name {
  font-weight: 600;
  color: #1a1a1a;
  margin: 0 0 4px 0;
}

.medicine-category {
  font-size: 12px;
  color: #8f9bb3;
}

.medicine-stats {
  display: flex;
  align-items: center;
  gap: 16px;
}

.stock-info {
  text-align: center;
}

.stock-count {
  display: block;
  font-size: 20px;
  font-weight: 700;
  color: #4a6cf7;
}

.stock-label {
  font-size: 12px;
  color: #8f9bb3;
}

.status-indicator {
  padding: 6px 12px;
  border-radius: 20px;
  font-size: 12px;
  font-weight: 600;
}

.status-indicator.in-stock {
  background: #e7f7ef;
  color: #0ca678;
}

.status-indicator.low-stock {
  background: #fff9e6;
  color: #f59f00;
}

.status-indicator.out-of-stock {
  background: #ffe3e3;
  color: #fa5252;
}

/* 导入模态框样式 */
.import-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.import-modal-content {
  background: white;
  border-radius: 16px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  width: 90%;
  max-width: 500px;
  max-height: 90vh;
  overflow-y: auto;
}

.import-modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 24px 10px;
  border-bottom: 1px solid #f0f2f5;
}

.import-modal-header h3 {
  margin: 0;
  color: #1a1a1a;
  font-size: 18px;
  font-weight: 600;
}

.close-button {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #8f9bb3;
  padding: 0;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: background-color 0.3s;
}

.close-button:hover {
  background-color: #f0f2f5;
}

.import-modal-body {
  padding: 20px 24px;
}

.drop-area {
  border: 2px dashed #e8eaf0;
  border-radius: 10px;
  padding: 40px 20px;
  text-align: center;
  margin-bottom: 30px;
  transition: all 0.3s;
  background-color: #fafbfc;
}

.drop-area.drag-over {
  border-color: #4a6cf7;
  background-color: rgba(74, 108, 247, 0.05);
}

.upload-icon {
  font-size: 48px;
  color: #8f9bb3;
  margin-bottom: 15px;
}

.drop-area p {
  margin: 10px 0;
  color: #555;
}

.upload-hint {
  font-size: 12px;
  color: #8f9bb3 !important;
}

.template-download {
  text-align: center;
}

.template-download h4 {
  margin-top: 0;
  margin-bottom: 10px;
  color: #1a1a1a;
}

.template-download p {
  margin: 5px 0 20px;
  color: #555;
}

.btn-download-template {
  background: #e8eaf0;
  border: none;
  padding: 10px 20px;
  border-radius: 10px;
  font-size: 14px;
  color: #555;
  cursor: pointer;
  transition: all 0.3s;
  display: inline-flex;
  align-items: center;
  gap: 8px;
}

.btn-download-template:hover {
  background: #d0d0d0;
  transform: translateY(-2px);
}
</style>